package com.junxonline.instant.admin.service.log.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junxonline.instant.dao.entity.model.log.LogLogin;
import com.junxonline.instant.dao.entity.vo.log.LogLoginVO;
import com.junxonline.instant.dao.mapper.log.LogLoginMapper;
import com.junxonline.instant.admin.service.log.LogLoginService;
import com.junxonline.instant.common.constant.CommonConstant;
import com.junxonline.instant.common.constant.DataSourceConstant;
import com.junxonline.instant.common.entity.common.CommonReqPage;
import com.junxonline.instant.common.entity.common.CommonRespPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 登录日志接口实现类
 *
 * @author JunX
 * @date 2021-06-24
 */
@Service
@Transactional
public class LogLoginServiceImpl extends ServiceImpl<LogLoginMapper, LogLogin> implements LogLoginService {

    @Autowired
    private LogLoginMapper logLoginMapper;

    /**
     * 查询登录日志列表
     *
     * @param vo 请求参数
     * @return CommonRespPage<LogLogin>
     */
    @Override
    @DS(DataSourceConstant.SHARDING)
    public CommonRespPage<LogLogin> queryList(CommonReqPage<LogLoginVO> vo) {
        LambdaQueryWrapper<LogLogin> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(vo.getQueryParams().getUsername()), LogLogin::getUsername, vo.getQueryParams().getUsername());
        wrapper.like(StrUtil.isNotBlank(vo.getQueryParams().getToken()), LogLogin::getToken, vo.getQueryParams().getToken());
        wrapper.eq(vo.getQueryParams().getType() != null, LogLogin::getType, vo.getQueryParams().getType());
        if (vo.getQueryParams().getOperationTime() != null) {
            wrapper.between(LogLogin::getOperationTime
                    , DateUtil.parseDateTime(vo.getQueryParams().getOperationTime()[0] + CommonConstant.QUERY_TIME_APPEND_START_TIME)
                    , DateUtil.parseDateTime(vo.getQueryParams().getOperationTime()[1] + CommonConstant.QUERY_TIME_APPEND_END_TIME));
        }
        wrapper.orderByDesc(LogLogin::getOperationTime);
        return CommonRespPage.success(logLoginMapper.selectPage(new Page<>(vo.getPage(), vo.getPageSize()), wrapper));
    }

}
